package com.polaris.live.ui.login

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.adapter.login.AppealAdapter
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.FormatUtils
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.ActivityAccountAppealBinding
import com.polaris.live.interface_bag.S3UploadCallback
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.resp.go_resp.AppealBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.getLongOrString
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.viewmodel.AccountAppealViewModel

/**
 * 账号申诉
 *
 * @author Created by 长空 on 2023/11/02/013 14:20
 */
class AccountAppealActivity :
    BaseVbActivity<AccountAppealViewModel, ActivityAccountAppealBinding>() {

    private lateinit var mAdapter: AppealAdapter

    private val userId: Long by lazy { intent.getLongOrString(CommonConst.Login.LOGIN_USER_ID, 0L) }

    override fun initView(savedInstanceState: Bundle?) {
        val email = CacheUtil.getAppealEmail()
        email?.let { mBinding.etEmail.setText(it) }

        mBinding.etAppeal.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                mBinding.tvTextLength.text = "${s?.length}/1500"

            }
        })

        mBinding.rvAppealPhoto.layoutManager = GridLayoutManager(this, 3)
        mAdapter = AppealAdapter()
        mAdapter.addData("")
        mBinding.rvAppealPhoto.adapter = mAdapter

        mViewModel.appealLiveData.observe(this) { resultState ->
            dismissLoading()
            parseState(resultState, {
                CacheUtil.setAppealEmail(mBinding.etEmail.text.toString().trim())
                ToastGravity.showGravity(StringUtils.getString(string.submit_appeal_successfully))
                finish()
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }

        mBinding.etEmail.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                super.afterTextChanged(s)
                val toString = mBinding.etEmail.text.toString()
                val trimmedStr = toString.replace("\\s+".toRegex(), "")  // 去掉所有空格

                if (trimmedStr.isEmpty()) {
                    mBinding.ivClear.visibility = View.INVISIBLE
                } else {
                    mBinding.ivClear.visibility = View.VISIBLE
                }
            }
        })

        mBinding.ivClear.setOnSingleClickListener {
            mBinding.etEmail.setText("")
        }

        mBinding.tvCommitAppeal.setOnSingleClickListener {
            val appeal = mBinding.etAppeal.text.toString().trim()
            val email = mBinding.etEmail.text.toString().trim()
            if (appeal.isEmpty()) {
                ToastGravity.showGravity(getString(string.please_state_complaint))
                return@setOnSingleClickListener
            } else if (email.isEmpty()) {
                ToastGravity.showGravity(getString(string.please_input_email))
                return@setOnSingleClickListener
            } else if (!FormatUtils.isEmail(email)) {
                ToastGravity.showGravity(getString(string.please_input_correct_email))
                return@setOnSingleClickListener
            }
            mAdapter.data.remove("")
            val list = mutableListOf<String>()

            showLoading(waitTime = 0)

            if (mAdapter.data.isNotEmpty()) {
                mAdapter.data.forEachIndexed { _, pic ->
                    ImageUtils.s3Upload(
                        pic,
                        AppConst.UpLoad.APPEAL,
                        callback = object : S3UploadCallback {
                            override fun onSuccess(url: String, size: Pair<Int, Int>?) {
                                list.add(url)
                                if (list.size == mAdapter.data.size) {
                                    mViewModel.appeal(
                                        AppealBean(
                                            userId = userId,
                                            uniqueId = AppModule.requireUniqueDeviceId(),
                                            content = appeal,
                                            pics = list,
                                            email = email
                                        )
                                    )
                                }
                            }

                            override fun onFailure(t: Throwable) {
                                LogExt.logE("--net", t)

                                ToastGravity.showGravity(t.message)

                                dismissLoading()
                            }
                        })
                }
            } else {
                mViewModel.appeal(
                    AppealBean(
                        userId = userId,
                        uniqueId = AppModule.requireUniqueDeviceId(),
                        content = appeal,
                        email = email
                    )
                )
            }
        }
    }
}